// ArrayBuffer转16进度字符串

const utils = {
    // arrayBuffer转16进制
    ab2hex: (buffer) => {
        const hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function (bit) {
                return ('00' + bit.toString(16)).slice(-2)
            }
        )
        return hexArr.join('')
    },
    // arrayBuffer转字符串
    arrayBufferToString: (buffer, encoding = 'utf-8') => {
        const decoder = new TextDecoder(encoding)
        return decoder.decode(buffer)
    },
    // 16进制转字符串
    hexToStr: (hex) => {
        let tmp = ''
        if (hex.length % 2 === 0) {
            for (let i = 0; i < hex.length; i += 2) {
                tmp += '%' + hex.charAt(i) + hex.charAt(i + 1)
            }
        }
        return decodeURIComponent(tmp)
    },
    // 16进制转10进制
    hex2int: (hexStr) => {
        let twoStr = parseInt(hexStr, 16).toString(2); // 将十六转十进制，再转2进制
        let bitNum = hexStr.length * 4; // 1个字节 = 8bit ，0xff 一个 "f"就是4位
        if (twoStr.length < bitNum) {
            while (twoStr.length < bitNum) {
                twoStr = "0" + twoStr;
            }
        }
        if (twoStr.substring(0, 1) === "0") {
            // 正数
            twoStr = parseInt(twoStr, 2); // 二进制转十进制
            return twoStr;
        } else {
            // 负数
            let twoStr_unsign = "";

            //console.log("hex2int--->" + parseInt(twoStr, 2));
            twoStr = parseInt(twoStr, 2) - 1; // 补码：(负数)反码+1，符号位不变；相对十进制来说也是 +1，但这里是负数，+1就是绝对值数据-1
            //console.log("hex2int--->" + twoStr);

            twoStr = twoStr.toString(2);
            twoStr_unsign = twoStr.substring(1, bitNum); // 舍弃首位(符号位)
            // 去除首字符，将0转为1，将1转为0   反码
            twoStr_unsign = twoStr_unsign.replace(/0/g, "z");
            twoStr_unsign = twoStr_unsign.replace(/1/g, "0");
            twoStr_unsign = twoStr_unsign.replace(/z/g, "1");

            //console.log("hex2int--->" + twoStr_unsign);
            //console.log("hex2int--->" + (-twoStr_unsign));
            twoStr = parseInt(-twoStr_unsign, 2);
            return twoStr;
        }
    },
    /**
     * 弹出框封装
     */
    showModal: (content, showCancel = false) => {
        uni.showModal({
            title: '提示',
            content,
            showCancel
        })
    },
    toast(title, duration = 1500) {
        uni.showToast({
            title: title,
            icon: 'none',
            duration: duration
        })
    }
}

export default utils
